/**
 * Copyright (c) 快宝网络 kuaidihelp.com Co., Ltd. All Rights Reserved 禁止外泄以及用于其它的商业用途
 */

/**
 * 下属驿站充值
 *  */
import React, { useEffect, useCallback, useState, useMemo } from 'react';
import StandardTable from '@/components/StandardTable';
import { Form, Row, Col, Button, message, Input } from 'antd';
import { connect } from 'dva';
import AddressCascader from '@/components/AddressCascader';
import ChargePostModal from './ChargePostModal';

const { Item: FormItem } = Form;

const ChargePost = ({
  dispatch,
  loading,
  form,
  chargingType = 'sms',
  userInfo,
  options,
  zyLoading,
}) => {
  const { getFieldDecorator, validateFields, resetFields } = form;
  const { branch, branchId } = userInfo;
  const { key } = options;
  const isZyAccount = key === 'post';

  const [tableData, setTableData] = useState({ list: [] });
  const [visible, setVisible] = useState(false);
  const [selectedRows, setSelectedRows] = useState([]);
  const [kbIds, setKbIds] = useState([]);
  const [cmIds, setCmIds] = useState([]);
  const [payInfo, setPayInfo] = useState({});

  const getList = useCallback(
    (params = {}) => {
      const payload = isZyAccount
        ? {
            type: 'area/getZyAccountList',
            payload: {
              page: params.pageNum || 1,
              size: 20,
              branch_id: params.code || branchId,
              keywords: params.keyword,
            },
          }
        : {
            type: 'area/subList',
            payload: {
              is_district: '0',
              pageNum: 1,
              recharge: 1,
              ...params,
            },
          };

      dispatch(payload).then(res => {
        const { list, paginations } = res;
        setTableData({
          list,
          pagination: {
            total: paginations.count,
            current: paginations.page,
            pageSize: paginations.pageSize,
            showQuickJumper: false,
            showSizeChanger: false,
          },
        });
      });
    },
    [dispatch, isZyAccount, branchId],
  );

  const onCharge = useCallback((kbId = []) => {
    setKbIds(kbId);
    setVisible(true);
  }, []);

  const onRowSelect = useCallback(e => {
    const kbId = e.map(i => i.kb_id);

    setKbIds(kbId);
    setSelectedRows(e);
  }, []);

  const onCancel = useCallback(
    () => {
      setVisible(false);
      resetFields();
      setPayInfo({});
    },
    [resetFields],
  );

  const freshCurrentPage = () => {
    setSelectedRows([]);
    setKbIds([]);
    setCmIds([]);
    setVisible(false);
    getList();
  };

  const onOk = useCallback(
    data => {
      const kb_id = kbIds.filter(i => i);

      if (kb_id.length === 0) {
        message.error('缺少kb_id，请稍后重试');
        return;
      }

      dispatch({
        type: 'area/charging',
        payload: {
          type: chargingType == 'sms' ? '1' : '2',
          kb_ids: kb_id.join(','),
          amount: data.money,
          isZyAccount: isZyAccount ? 1 : 0,
        },
      })
        .then(res => {
          const { data: result } = res || {};
          if (isZyAccount) {
            setPayInfo({
              money: result.total_money,
              qrCodeUrl: `http://m.kuaidihelp.com/order/wxqrcode?data=${
                result.return_url
              }&logo=alipay`,
              order_number: result.order_number,
              count: chargingType == 'sms' ? result.total_sms_count : result.total_money,
              chargingType, // 充值类型
            });
            return;
          }
          freshCurrentPage();
        })
        .catch(error => {
          console.log(error);
        });
    },
    [dispatch, getList, cmIds, kbIds, chargingType],
  );

  const onBatchCharge = useCallback(
    () => {
      const kbId = selectedRows.map(i => i.kb_id);
      setKbIds(kbId);
      setVisible(true);
    },
    [selectedRows],
  );

  const columns = useMemo(
    () => [
      {
        title: '驿站id',
        dataIndex: 'cm_id',
        key: 'cm_id',
        align: 'center',
      },
      {
        title: '手机号',
        dataIndex: 'phone',
        key: 'phone',
        align: 'center',
      },
      {
        title: '驿站名称',
        dataIndex: 'company_name',
        key: 'company_name',
        align: 'center',
        render: (company_name, { inn_name }) => company_name || inn_name,
      },
      {
        title: '剩余免费短信/可消费余额',
        dataIndex: 'sms_balance',
        key: 'sms_balance',
        align: 'center',
        render: (_, { sms_balance, avail_money }) => `${sms_balance || 0} / ${avail_money || 0}`,
      },
      {
        title: '操作',
        render: (_, { kb_id }) => <a onClick={() => onCharge([kb_id])}>为他充值</a>,
      },
    ],
    [onCharge],
  );

  const onSearch = () => {
    validateFields((err, value) => {
      if (err) return;
      const { codeArr = [], ...rest } = value;
      const code = [...codeArr][codeArr.length - 1];
      getList({ code, ...rest });
    });
  };

  const onTableChange = ({ current }) => {
    getList({
      pageNum: current,
    });
  };

  useEffect(
    () => {
      getList();
    },
    [getList],
  );

  return (
    <>
      <Form layout="inline">
        <FormItem>
          {getFieldDecorator('codeArr', {
            initialValue: branch.map(i => i.code),
          })(
            isZyAccount ? (
              <AddressCascader level={3} type="search" width={400} companyId={branchId} request />
            ) : (
              <AddressCascader
                level={4}
                fieldNames={{ label: 'name', value: 'code' }}
                width={400}
                branch={branch}
                request
                changeOnSelect
              />
            ),
          )}
        </FormItem>
        <FormItem>
          {getFieldDecorator('keyword')(
            <Input style={{ width: 300 }} placeholder="请输入手机号码、驿站名称或驿站id查找" />,
          )}
        </FormItem>
        <FormItem>
          <Button type="primary" onClick={onSearch} loading={loading}>
            查询
          </Button>
        </FormItem>
      </Form>
      <StandardTable
        rowKey="id"
        loading={loading || zyLoading}
        data={tableData}
        columns={columns}
        selectedRows={selectedRows}
        onSelectRow={onRowSelect}
        onChange={onTableChange}
      />
      <Row style={{ marginTop: 20 }} type="flex" justify="start">
        <Col>
          <Button type="primary" disabled={selectedRows.length == 0} onClick={onBatchCharge}>
            批量充值
          </Button>
        </Col>
      </Row>
      <ChargePostModal
        refreshPage={freshCurrentPage}
        payInfo={payInfo}
        visible={visible}
        onCancel={onCancel}
        onOk={onOk}
        selectedRows={selectedRows}
      />
    </>
  );
};

export default connect(({ loading, user, area, setting }) => ({
  chargingType: area.chargingType, // sms，money
  userInfo: user.currentUser.user_info,
  loading: loading.effects['area/subList'],
  zyLoading: loading.effects['area/getZyAccountList'],
  ...setting,
}))(React.memo(Form.create()(ChargePost)));
